<template>
  <div>
    <a-menu
      mode="inline"
      class="fixed-sider"
      v-model:selectedKeys="selectedKeys"
      :openKeys="openKeys"
      @openChange="onOpenChange"
      @select="onSelect"
    >
      <template v-for="item in menuTree" :key="item.id">
        <template v-if="!item.children">
          <a-menu-item :key="item.key">
            <template #icon>
              <IconAntdv :icon="item.icon" />
              <!-- <PieChartOutlined /> -->
            </template>
            {{ item.name }}
          </a-menu-item>
        </template>
        <template v-else>
          <SubMenu :menu-info="item" :key="item.key" />
        </template>
      </template>
    </a-menu>
  </div>
</template>
<script>
import { computed, defineComponent, toRefs, reactive, onBeforeUnmount, watch } from 'vue'
import SubMenu from '@/components/main/SubMenu.vue'

export default defineComponent({
  name: 'MainSider',
  components: {
    SubMenu
    // PieChartOutlined
  },
  props: {
    menuList: {
      type: Array,
      default: () => []
    },
    menuTree: {
      type: Array,
      default: () => []
    },
    defaultSelectedKeys: {
      type: Array,
      default: () => []
    },
    defaultOpenKeys: {
      type: Array,
      default: () => []
    }
  },
  emits: ['goPage'],
  setup (props, context) {
    const { menuList, menuTree, defaultSelectedKeys, defaultOpenKeys } = toRefs(props)
    const rootId = '0'

    const getRootKeys = computed(() => {
      const list = menuTree.value.filter(item => item.pid === rootId)
      return list.map(item => item.key)
    })

    const state = reactive({
      rootSubmenuKeys: getRootKeys.value,
      selectedKeys: defaultSelectedKeys.value,
      openKeys: defaultOpenKeys.value
    })
    watch(defaultSelectedKeys, val => {
      state.selectedKeys = val
    })
    watch(defaultOpenKeys, val => {
      state.openKeys = val
    })

    const onOpenChange = openKeys => {
      const latestOpenKey = openKeys.find(key => state.openKeys.indexOf(key) < 0)

      if (state.rootSubmenuKeys.indexOf(latestOpenKey) < 0) {
        state.openKeys = openKeys
      } else {
        state.openKeys = latestOpenKey ? [latestOpenKey] : []
      }
    }

    const onSelect = ({ key }) => {
      const currMenu = menuList.value.filter(item => item.key === key)[0]
      context.emit('goPage', currMenu.url)
    }

    onBeforeUnmount(() => {
      console.log('un sider')
    })

    return {
      ...toRefs(state),
      getRootKeys,
      onOpenChange,
      onSelect
    }
  }
})
</script>

<style lang="less">
// .fixed-sider.ant-menu-inline .ant-menu-item::after {
//   left: 0;
//   right: inherit;
//   border-width: 6px;
// }
</style>
